package com.example.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.daoman.User;
import com.example.excel.DemoData;
import com.example.excel.DemoDataListener;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//超级管理接口设计
@RequestMapping("/boos")
@RestController
public class BoosInterFace {

    //    文件批量导入操作

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/in")
    public String in(MultipartFile file) throws IOException {
//        创建监听器
        EasyExcel.read(file.getInputStream(), User.class, new DemoDataListener(userMapper)).sheet().doRead();
        return "success";
    }

    //    数据写出函数
    private List<User> data() {
//        数据查询
        Map<String,Object> map = new HashMap<>();
        List<User> allList = userMapper.getAllList(map);
        return allList;
    }


    //    文件写出操作
    @RequestMapping("/out")
    public String out(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = "test";
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("模板").doWrite(data());
        return "success";
    }

}
